package com.my.study.lock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore:三个车位,停满为0,离开后累加到3(进执行加,出执行减)
 */
public class SemaphoreDemo {

    private static final int NUM = 3;

    public static void main(String[] args) {
        // 资源数量为3,6个线程争夺
        Semaphore semaphore = new Semaphore(NUM);
        for (int i = 0; i < 6; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println("第"+ finalI +"线程获取到资源");
                    // 暂用3秒钟释放资源
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println("第"+ finalI +"线程暂用3秒钟释放资源");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },"t"+i).start();
        }
    }
}
